package com.example.course.controller;

import com.example.course.bean.Admin;
import com.example.course.bean.Student;
import com.example.course.bean.Teacher;
import com.example.course.bean.User;
import com.example.course.bean.vo.UserLoginByPassVo;
import com.example.course.service.AdminService;
import com.example.course.service.StudentService;
import com.example.course.service.TeacherService;
import com.example.course.vo.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class UserLoginController {
    @Resource
    private AdminService adminService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private StudentService studentService;
    @RequestMapping("/course/login")
    public Object userLogin(UserLoginByPassVo userLoginByPassVo, HttpSession session){
        System.out.println(userLoginByPassVo);
        if (userLoginByPassVo.getType().equals("admin")){
            Admin admin =adminService.getAdmin(new Admin(userLoginByPassVo.getAccount(),userLoginByPassVo.getPassword()));
            if (admin != null){
                session.setAttribute("user",new User(userLoginByPassVo.getType(),admin));
                return "index";
            }else {
                return "login";
            }
        }else if (userLoginByPassVo.getType().equals("teacher")){
            Teacher teacher =teacherService.getTeacher(new Teacher(userLoginByPassVo.getAccount(),userLoginByPassVo.getPassword()));
            if (teacher != null){
                session.setAttribute("user",new User(userLoginByPassVo.getType(),teacher));
                return "index";
            }else {
                return "login";
            }
        } else if (userLoginByPassVo.getType().equals("student")){
            Student student =studentService.getStudent(new Student(userLoginByPassVo.getAccount(),userLoginByPassVo.getPassword()));
            if (student != null){
                session.setAttribute("user",new User(userLoginByPassVo.getType(),student));
                return "index";
            }else {
                return "login";
            }
        }else {
            return "login";
        }
    }
    @RequestMapping("/course/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/course/getSession")
    @ResponseBody
    public Result getSession(HttpSession session){
        Object user = session.getAttribute("user");
        return new Result(user);
    }
}
